package logger

import (
	"fmt"
	"io"
	"os"
	"time"

	"github.com/fatih/color"
	"github.com/sirupsen/logrus"
)

var (
	// 颜色定义
	red     = color.New(color.FgRed, color.Bold)
	green   = color.New(color.FgGreen, color.Bold)
	yellow  = color.New(color.FgYellow, color.Bold)
	blue    = color.New(color.FgBlue, color.Bold)
	cyan    = color.New(color.FgCyan, color.Bold)
	magenta = color.New(color.FgMagenta, color.Bold)
	white   = color.New(color.FgWhite, color.Bold)

	// 全局日志实例
	Logger *logrus.Logger

	// 当前公众号名称上下文
	currentGzhName string
)

// ColoredFormatter 彩色日志格式化器
type ColoredFormatter struct {
	TimestampFormat string
}

// Format 格式化日志
func (f *ColoredFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	timestamp := entry.Time.Format(f.TimestampFormat)

	// 根据日志级别选择颜色
	var levelColor *color.Color
	var levelText string

	switch entry.Level {
	case logrus.PanicLevel:
		levelColor = red
		levelText = "PANIC"
	case logrus.FatalLevel:
		levelColor = red
		levelText = "FATAL"
	case logrus.ErrorLevel:
		levelColor = red
		levelText = "ERROR"
	case logrus.WarnLevel:
		levelColor = yellow
		levelText = "WARN "
	case logrus.InfoLevel:
		levelColor = green
		levelText = "INFO "
	case logrus.DebugLevel:
		levelColor = blue
		levelText = "DEBUG"
	case logrus.TraceLevel:
		levelColor = cyan
		levelText = "TRACE"
	default:
		levelColor = white
		levelText = "UNKNOWN"
	}

	// 格式化消息，自动添加公众号名称
	message := entry.Message
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}

	formattedMessage := fmt.Sprintf("[%s] %s %s",
		cyan.Sprint(timestamp),
		levelColor.Sprint(levelText),
		message,
	)

	// 添加字段信息
	if len(entry.Data) > 0 {
		fields := ""
		for k, v := range entry.Data {
			fields += fmt.Sprintf(" %s=%v", magenta.Sprint(k), v)
		}
		formattedMessage += fields
	}

	return []byte(formattedMessage + "\n"), nil
}

// InitLogger 初始化日志
func InitLogger() {
	Logger = logrus.New()

	// 设置日志级别
	Logger.SetLevel(logrus.InfoLevel)

	// 设置彩色格式化器
	Logger.SetFormatter(&ColoredFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	// 设置输出
	Logger.SetOutput(os.Stdout)
}

// SetGzhName 设置当前公众号名称
func SetGzhName(gzhName string) {
	currentGzhName = gzhName
}

// GetGzhName 获取当前公众号名称
func GetGzhName() string {
	return currentGzhName
}

// Info 信息日志
func Info(format string, args ...interface{}) {
	Logger.Infof(format, args...)
}

// Error 错误日志
func Error(format string, args ...interface{}) {
	Logger.Errorf(format, args...)
}

// Warn 警告日志
func Warn(format string, args ...interface{}) {
	Logger.Warnf(format, args...)
}

// Debug 调试日志
func Debug(format string, args ...interface{}) {
	Logger.Debugf(format, args...)
}

// Success 成功日志（绿色）
func Success(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	green.Printf("[%s] SUCCESS %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// Processing 处理中日志（蓝色）
func Processing(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	blue.Printf("[%s] PROCESS %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// ArticleInfo 文章信息日志（青色）
func ArticleInfo(title string, args ...interface{}) {
	message := title
	if len(args) > 0 {
		message += " " + fmt.Sprintf(args[0].(string), args[1:]...)
	}
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	cyan.Printf("[%s] ARTICLE %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// ImageInfo 图片信息日志（洋红色）
func ImageInfo(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	magenta.Printf("[%s] IMAGE  %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// RedisInfo Redis 信息日志
func RedisInfo(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	blue.Printf("[%s] REDIS  %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// ESInfo Elasticsearch 信息日志
func ESInfo(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	green.Printf("[%s] ES     %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// MinioInfo MinIO 信息日志
func MinioInfo(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	cyan.Printf("[%s] MINIO  %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// StatsInfo 统计信息日志
func StatsInfo(format string, args ...interface{}) {
	message := fmt.Sprintf(format, args...)
	if currentGzhName != "" {
		message = fmt.Sprintf("%s %s", currentGzhName, message)
	}
	white.Printf("[%s] STATS  %s\n", time.Now().Format("2006-01-02 15:04:05"), message)
}

// SetLevel 设置日志级别
func SetLevel(level string) {
	switch level {
	case "debug":
		Logger.SetLevel(logrus.DebugLevel)
	case "info":
		Logger.SetLevel(logrus.InfoLevel)
	case "warn":
		Logger.SetLevel(logrus.WarnLevel)
	case "error":
		Logger.SetLevel(logrus.ErrorLevel)
	default:
		Logger.SetLevel(logrus.InfoLevel)
	}
}

// SetOutput 设置输出
func SetOutput(output io.Writer) {
	Logger.SetOutput(output)
}

// WithFields 带字段的日志
func WithFields(fields logrus.Fields) *logrus.Entry {
	return Logger.WithFields(fields)
}
